const express = require('express')
const app = express()
const jwt = require('jsonwebtoken')
const JWT_SECRET_KEY = 'JWT_SECRET_KEY'
const response = require('./pool/Response')
//配置跨域
const cors = require('cors')
app.use(cors({
    origin:'*'
}))

//解析post请求参数
app.use(express.urlencoded())
//自定义token验证中间件
const tokenTools = function(req,res,next){
    //若请求是/user/login 则不拦截，直接向后执行
    if(req.path == '/user/login'){
      next()
      return  
    }
    //执行token验证
    let token = req.headers['authorization'];
    try {
        let payload = jwt.verify(token,JWT_SECRET_KEY)
        req.tokenPayload = payload //将token中存储的数据赋值给req，这样在后续的业务中就可以使用req.tokenPayload获取这些数据
    } catch (error) {
        res.send(response.error(401,'请先登录'))
        return
    }
    next()
}
app.use(tokenTools)
//引入外部路由
app.use(require('./router/MovieActor'))
app.use(require('./router/MovieDirctor'))
app.use(require('./router/MovieInfo'))
app.use(require('./router/MovieThumb'))
app.use(require('./router/Cinema'))
app.use(require('./router/CinemaRoom'))
app.use(require('./router/ShowingonPlan'))
app.use(require('./router/Admin'))
app.get('/',(res,req) => {
    req.send('hello world')
})

app.listen(3000,()=>{
    console.log('百慕大后端服务已启动...')
})
